package com.beiing.tianshuai.tianshuai.mine.ui;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.MyOrderAdapter;
import com.beiing.tianshuai.tianshuai.entity.CommonBean;
import com.beiing.tianshuai.tianshuai.entity.MyOrderBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.event.EventConstant;
import com.beiing.tianshuai.tianshuai.event.messages.OrderListEvent;
import com.beiing.tianshuai.tianshuai.fragment.BaseLazyLoadFragment;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderDeleteBean;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderExtendTransportBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.MyOrderPresenter;
import com.beiing.tianshuai.tianshuai.mine.view.MyOrderViewImpl;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * A simple {@link Fragment} subclass.
 * 我的订单分类列表页
 *
 * @author 杨金达
 */
public class MyOrderFragment extends BaseLazyLoadFragment implements MyOrderViewImpl {

    /**
     * 订单列表
     */
    @BindView(R.id.rv_order_list)
    RecyclerView mRvOrderList;

    /**
     * 空警告
     */
    @BindView(R.id.txt_empty_warning)
    TextView mTxtEmptyWarning;

    /**
     * 刷新头布局
     */
    @BindView(R.id.srl_my_refresh_layout)
    SmartRefreshLayout mSrlMyRefreshLayout;

    /**
     * 刷新头布局
     */
    @BindView(R.id.refresh_layout_header)
    MyRefreshHeader mRefreshLayoutHeader;

    /**
     * tag
     */
    private static final String TAG = "MyOrderFragment";

    /**
     * 当前列表订单类型
     */
    private int mType;

    /**
     * 是否准备
     */
    private boolean isPrepared;

    /**
     * 是否已经加载一次
     */
    private boolean isLoadedOnce;

    /**
     * content view
     */
    private View mContentView;

    /**
     * user id
     */
    private String mUid;

    /**
     * context
     */
    private Context mContext;

    /**
     * the adapter for order recycler view
     */
    private MyOrderAdapter mAdapter;

    /**
     * the presenter for my order
     */
    private MyOrderPresenter mPresenter;

    /**
     * the page size for order list
     */
    private static final int PAGE_SIZE = 20;

    /**
     * is refresh layout is refreshing
     */
    private boolean isRefresh;

    /**
     * Have all the orders been loaded
     */
    private boolean isLoadFinished;

    /**
     * 用于接收其他界面传递过来的消息判断是否需要更新列表信息
     */
    private RxBus mRxBus;

    /**
     * get a new order fragment
     *
     * @param uid  the user id
     * @param type the order type
     * @return fragment
     */
    public static MyOrderFragment newInstance(String uid, int type) {
        MyOrderFragment fragment = new MyOrderFragment();
        Bundle bundle = new Bundle();
        bundle.putString("uid", uid);
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = inflater.inflate(R.layout.fragment_my_order, container, false);
            mUnbinder = ButterKnife.bind(this, mContentView);
            mContext = getActivity();
            Bundle bundle = getArguments();
            // 获取当前主页用户id
            if (bundle != null) {
                mUid = bundle.getString("uid");
                mType = bundle.getInt("type");
            }
            mPresenter = new MyOrderPresenter(this);
            isPrepared = true;
            initRecyclerView();
            initRefreshLayout();
            initListener();
            lazyLoad();
            initRxBus();
        }

        //因为共用一个Fragment视图，所以当前这个视图已被加载到Activity中，必须先清除后再加入Activity
        ViewGroup parent = (ViewGroup) mContentView.getParent();
        if (parent != null) {
            parent.removeView(mContentView);
        }
        return mContentView;
    }

    /**
     * 初始化RxBus
     */
    private void initRxBus() {
        mRxBus = RxBus.getInstanceBus();
        Disposable disposable = mRxBus.doSubscribe(OrderListEvent.class,
                new Consumer<OrderListEvent>() {
                    @Override
                    public void accept(OrderListEvent msgEvent) {
                        int type = msgEvent.getType();
                        String data = (String) msgEvent.getData();
                        switch (type) {
                            case EventConstant.EVENT_TYPE_UPDATE_ORDER_LIST:
                                refreshOrderList();
                                LogUtils.i(data, "rxBus");
                                break;
                            default:
                                LogUtils.e("未找到相关消息类型", "rxBus");
                                break;
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) {
                        LogUtils.e(throwable.getMessage(), TAG);
                    }
                });
        mRxBus.addSubscription(this, disposable);
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || isLoadedOnce) {
            return;
        }
        mPresenter.getMyOrderInfoResult(mUid, mType, "-1", 20);
    }

    private void initRecyclerView() {
        mAdapter = new MyOrderAdapter(mContext);
        mRvOrderList.setAdapter(mAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        mRvOrderList.setNestedScrollingEnabled(false);
        mRvOrderList.setLayoutManager(linearLayoutManager);
    }

    /**
     * 初始化refresh layout
     * 设置下拉和上拉动作的listener
     */
    private void initRefreshLayout() {
        mSrlMyRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        ClassicsFooter footer = new ClassicsFooter(mContext);
        footer.setBackgroundColor(Color.WHITE);
        mSrlMyRefreshLayout.setRefreshFooter(footer);
        // =================== 下拉刷新 =====================
        mSrlMyRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshOrderList();
            }
        });
        // =================== 上拉加载 =====================
        mSrlMyRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinished) {
                    isRefresh = false;
                    mPresenter.getMyOrderInfoResult(
                            mUid,
                            mType,
                            mAdapter.getLastItem() == null ? "-1" : mAdapter.getLastItem().getId(),
                            PAGE_SIZE
                    );
                }
            }
        });
    }

    /**
     * 刷新订单列表
     */
    private void refreshOrderList() {
        isRefresh = true;
        isLoadFinished = false;
        mPresenter.getMyOrderInfoResult(
                mUid,
                mType,
                "-1",
                PAGE_SIZE
        );
    }

    private void initListener() {
        // 按钮点击
        mAdapter.setListener(new MyOrderAdapter.OnClickListener() {

            @Override
            public void onPreviewClickListener(int position, String orderId) {
                Intent intent = new Intent(mContext, ETicketActivity.class);
                intent.putExtra("oid", orderId);
                startActivity(intent);
            }

            @Override
            public void onDeleteClickListener(final int position, final String orderId) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog, "确定要删除该订单吗？", new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            mPresenter.getDelRequestResult(orderId, position);
                            dialog.dismiss();
                        } else {
                            dialog.dismiss();
                        }
                    }
                }).setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }

            @Override
            public void onDelayInReceivingClickListener(final int position, final MyOrderBean.DataBean.ResultBean bean) {
                boolean isExtend = TextUtils.equals(bean.getIsExtend(), "1");
                if (isExtend) {
                    showShortText("您已申请过延迟收货");
                } else {
                    final String orderId = bean.getId();
                    CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                            "只能申请一次延长收货\n确认继续申请吗？", new CustomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            if (confirm) {
                                mPresenter.getDelayInReceivingResult(orderId, bean);
                                dialog.dismiss();
                            } else {
                                dialog.dismiss();
                            }
                        }
                    }).setNegativeButton("取消").setPositiveButton("确认").setTitle("提示");
                    dialog.setCanceledOnTouchOutside(true);
                    dialog.show();
                }
            }

            @Override
            public void onCheckLogisticsClickListener(int position, String orderId) {
                OrderTransportActivity.start(mContext, orderId);
            }

            @Override
            public void onApplyForAfterSalesClickListener(int position, String orderId) {
                OrderApplyAfterSaleActivity.start(mContext, orderId);
            }

            @Override
            public void onToEvaluateClickListener(int position, MyOrderBean.DataBean.ResultBean orderBean) {
                OrderCommentActivity.start(
                        mContext,
                        orderBean.getAid(),
                        UserInfoBean.getUid(mContext),
                        orderBean.getId(),
                        orderBean.getCover(),
                        orderBean.getPhoto(),
                        orderBean.getName(),
                        "添加评价"
                );
            }

            @Override
            public void onConfirmReceiptClickListener(int position, String orderId) {

            }

            @Override
            public void onRemindTheDeliveryClickListener(int position, String orderId) {

            }

            @Override
            public void onCancelTheAfterSaleClickListener(int position, String orderId) {
                OrderAfterSaleStateActivity.start(getActivity(), orderId);
            }

            @Override
            public void onApplyAfterSaleAgainClickListener(int position, String orderId) {

            }

            @Override
            public void onItemClickListener(int position, MyOrderBean.DataBean.ResultBean bean) {
                OrderDetailActivity.start(mContext, bean.getId());
            }
        });
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(MyOrderBean bean) {

        List<MyOrderBean.DataBean.ResultBean> result = bean.getData().getResult();
        LogUtils.i(result.toString(), "Order Info");
        isLoadedOnce = true;

        // 当前网络请求返回的条目数量
        int count = bean.getData().getCount();

        // 根据当前的刷新或加载状态更新或添加数据
        if (count > 0 && count < PAGE_SIZE) {
            if (isRefresh) {
                mAdapter.updateData(result);
            } else {
                mAdapter.appendData(result);
            }
            isLoadFinished = false;
        } else if (count == PAGE_SIZE) {
            if (isRefresh) {
                mAdapter.updateData(result);
            } else {
                mAdapter.appendData(result);
            }
            isLoadFinished = false;
        } else {
            if (isRefresh) {
                mAdapter.clearData();
            }
            isLoadFinished = true;
        }

        // 判断当前列表数据是否为空 并且改变empty warning的显示状态
        if (mTxtEmptyWarning != null) {
            mTxtEmptyWarning.setVisibility(mAdapter.isEmpty() ? View.VISIBLE : View.GONE);
        }

        // 结束刷新布局动画
        if (isRefresh) {
            if (mSrlMyRefreshLayout != null && mSrlMyRefreshLayout.isRefreshing()) {
                mSrlMyRefreshLayout.setLoadmoreFinished(isLoadFinished);
                mSrlMyRefreshLayout.finishRefresh(true);
            }
        } else {
            if (mSrlMyRefreshLayout != null && mSrlMyRefreshLayout.isLoading()) {
                mSrlMyRefreshLayout.setLoadmoreFinished(isLoadFinished);
                mSrlMyRefreshLayout.finishLoadmore(true);
            }
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        LogUtils.e(throwable.getMessage(), "OrderRequestError");
        showShortText("获取订单数据失败");
    }

    @Override
    public void getCancelResult(CommonBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                showShortText("取消成功");
                mPresenter.getMyOrderInfoResult(mUid, mType, "-1", 20);
                break;
            default:
                showShortText("取消失败");
                break;
        }
    }

    @Override
    public void getDelResult(OrderDeleteBean bean, int position) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                mAdapter.removeData(position);
                showShortText("删除成功");
                break;
            case 401:
                showShortText("参数有误");
                break;
            case 202:
                showShortText("删除失败");
                break;
            default:
                LogUtils.e("未知请求结果", TAG);
                break;
        }
    }

    @Override
    public void onRequestDelayInReceivingSuccess(OrderExtendTransportBean bean, MyOrderBean.DataBean.ResultBean orderBean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                orderBean.setIsExtend("1");
                break;
            case 201:
                showShortText("请不要重复申请");
                break;
            default:
                LogUtils.e("未知请求结果返回类型", TAG);
                break;
        }
    }

    @Override
    public void onRequestDelayInReceivingError(Throwable throwable) {
        LogUtils.e(throwable.getMessage(), TAG);
        showShortText("请求失败");
    }

    @Override
    public void onDestroy() {
        //取消订阅防止内存泄漏
        if (mRxBus != null) {
            mRxBus.unSubscribe(this);
        }
        super.onDestroy();
    }
}
